import React from 'react';
import { observer, inject } from 'mobx-react';
import * as mobx from 'mobx';
import { getAntd,getEcCom,getLabel } from '../../util/convert';
import WeaSapBrowser from '../../public/wea-sap-browser/single';
import objectAssign from 'object-assign';
import * as Util from '../../util/formUtil';
import * as FieldUtil from '../../util/public/fieldUtil';
import { getInvoiceFid } from '../../util/public/invoiceUtil';
import * as OtherModule from '../../util/otherModule';
import * as _ from '../../util/public/common';

@inject('globalStore', 'layoutStore')
@observer
export default class BrowserElement extends React.Component{
    doChangeEvent = (value) => {
        const { fieldMark,layoutStore } = this.props;
		layoutStore.changeSingleFieldValue(fieldMark, {value: value});
	}
    doBrowChangeEvent = (ids, names, datas) => {
        const valueInfo = { value: ids || '', specialobj:datas || []};
        const { fieldMark,rowIndex,fieldAttr,baseProps,layoutStore } = this.props;
        const { fieldid,isDetail,detailtype } = baseProps;
        let variable = {};
        if(detailtype === 141){     //人力资源条件值转换
			valueInfo.value = FieldUtil.spellResourceCondition(datas);
        }
        layoutStore.changeSingleFieldValue(fieldMark, valueInfo, variable);
        //触发浏览按钮变更事件
		Util.doDefinitionCallBackFun(fieldid, rowIndex, ids, datas, fieldAttr);
    }
    doSapBrowChangeEvent = (datas) => {
        let changeDatas = {};
        datas && datas.map(item =>{
            changeDatas = {...changeDatas, ...item};
        });
        this.props.layoutStore.changeMoreFieldData(changeDatas);
    }
    render() {
        const { WeaBrowser,WeaDatePicker,WeaTimePicker } = getEcCom();
        const { fieldMark,fieldAttr,symbol,rowIndex,cellObj,fieldObj } = this.props;
        let { baseProps } = this.props;
        const { viewAttr,fieldid,fieldName,isDetail,detailtype } = baseProps;

        let specialobj  = fieldObj.specialobj ? mobx.toJS(fieldObj.specialobj) : [];
        let browserProp  = this.getBrowserProp(detailtype, fieldAttr.fielddbtype);
        browserProp.type = detailtype;
        browserProp.replaceDatas = specialobj;
        this.extendBrowserProp(browserProp, fieldid, isDetail, detailtype);
        this.extendDateProp(baseProps);
        let inputStyle = {};
        if(viewAttr !== 1 && symbol.indexOf("mc_") > -1){
            inputStyle["min-width"] = "150px";
        }
        browserProp.inputStyle = inputStyle;
        if(detailtype !== 34)   //请假类型
            browserProp.resize= (viewAttr !== 1);
        let el;
        if(detailtype === 2){
            el = <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@ungkn5`}
                    {...baseProps}
                    onChange={this.doChangeEvent}
                 />
        }else if(detailtype === 290){
            el = <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@011nck`}
                {...baseProps}
                onChange={this.doChangeEvent}
                showTime
                format={"yyyy-MM-dd HH:mm"}
            />
        }else if(detailtype === 19){
            baseProps.value = FieldUtil.convertTimeValue(baseProps.value);  //时间值补零
            if(baseProps.value.length > 5){
                baseProps.formatPattern = 1;
                baseProps.format = "HH:mm:ss";
            }
            el = <WeaTimePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaTimePicker@vjvgsn`}
                    {...baseProps}
                    onChange={this.doChangeEvent}
                 />
        }else if(detailtype === 118 || detailtype === 124 || detailtype === 125 || detailtype === 126){
            //只读，特殊字段处理： 空会议室使用情况、计划、目标、报告
            const linkUrl = browserProp.linkUrl;
            let valueSpan = '';
            specialobj.map(v =>{
                if(linkUrl){
                    valueSpan = valueSpan + `<a href='${linkUrl}${v.id}' target='_new'>${v.name}</a> `;
                }else{
                    valueSpan = valueSpan + v.name + ' ';
                }
            });
            if(detailtype === 118){     //会议室使用情况
                valueSpan =  `<a href='/spa/meeting/static/index.html#/main/meeting/RoomPlan' target='_new'>${getLabel(15881,'会议室使用情况')}</a>`;
            }
            el =  (
                <div>
                    <span dangerouslySetInnerHTML={{__html: valueSpan}}></span>
                    <input type='hidden' name={fieldName} id={fieldName} value={baseProps.value}/>
                </div>
            )
        }else if(detailtype === 226){
            const weaBrowserProps = {...objectAssign({}, browserProp, baseProps)};
            el = <WeaSapBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaSapBrowser@mkc69m`}
                    weaBrowserProps={weaBrowserProps}
                    onChange={this.doSapBrowChangeEvent}
                />
        }else{
            el = <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@j1zg9h`}
                    {...objectAssign({}, browserProp, baseProps)}
                    selectSize='default'
                    onChange={this.doBrowChangeEvent}
                    // onAssociativeDataChange={this.doAssociativeDataChange}
                    addOnClick={this.clickAddBtn}
                />
        }
        return el;
    }
    //获取浏览框相关的表单字段值
    getBrowserProp(detailtype, fielddbtype){
        const { rowIndex,cellObj,globalStore,layoutStore } = this.props;
        const { isprint, useInvoiceCloud = false  } = globalStore.commonParam;
        const isCusBrow = (detailtype === 161 || detailtype ===162 || detailtype === 256 || detailtype === 257);
        const browKey = isCusBrow  ? detailtype +"_"+fielddbtype : detailtype.toString();
        const { browserInfo,fieldAttrMap,odocInfo } = layoutStore;
        let browProp = _.cloneDeep(browserInfo[browKey] || {});
        if(_.isEmpty(browProp))
            return browProp;

        browProp = {...browProp, ...(browProp.otherParams||{})};
        let relateFieldValue = {};
        browProp.relateFieldid && browProp.relateFieldid.map(field =>{
            const fieldid = field.split("_")[0];
            const isDetail = field.split("_")[1] === "1";
            const fieldAttr = fieldAttrMap.get(fieldid);
            let key = fieldAttr.fieldname;
            if(key){
                if(isDetail)
                    key = fieldAttr.tableName+"_"+key;
                if(isCusBrow)   //避免自定义浏览框依赖字段fieldname与其它参数重复
                    key = `${key.toLowerCase()}_${_.get(browProp, ["dataParams","currenttime"])}`;
                relateFieldValue[key] = FieldUtil.getRelateFieldValue(fieldid, rowIndex);
            }
        });
        let dataParams = browProp.dataParams || {};
        dataParams = {...dataParams, ...relateFieldValue};
        browProp.dataParams = dataParams;

        const curfieldid = cellObj.field.toString();
        if((detailtype ===9 || detailtype === 37) && "docFieldId" in odocInfo && odocInfo.docFieldId.toString() === curfieldid){
            //正文点击切换Tab
            browProp.onLinkClick = () =>{
                WfForm.switchTab("odoc");
            }
            browProp.hideOps = odocInfo.newTextNodes === true;
            browProp.hideSelect = odocInfo.newTextNodes === true;
        }
        if(parseInt(isprint) !== 1 && (detailtype === 87 || detailtype === 184)){
            browProp.extraElement = <span>
                <a href='/spa/meeting/static/index.html#/main/meeting/RoomPlan' target='_new'>{getLabel(15881,'会议室使用情况')}</a>
            </span>
        }
        if(useInvoiceCloud == true && (detailtype === 292 || detailtype === 293)){
            browProp.onBrowerClick = this.onBrowerClick;
        }
        return browProp;
    }

    onBrowerClick=()=>{
        const { fieldMark, baseProps }=this.props;
        const { value } = baseProps
        const { invoiceCloudInfo={} } = this.props.globalStore;
        if(!invoiceCloudInfo.token) return;
        let valueobj = this.getECID_FID();
        const fun = (fid)=>{
            window.invoiceBrowser = ecCom.WeaTools.createDialog({
                title: getLabel(516434,'我的票夹'),
                url:this.getInvoiceCloudUrl(fieldMark,fid),
                icon:"icon-coms-workflow",
                iconBgcolor:"#0079DE",
                style:{width:"758px",height:600},
                callback: (datas)=>{ // 数据通信
                },
                onCancel: ()=>{ // 关闭通信
                    window.invoiceBrowser=null;
                }
            }, undefined, (dialog) => {
                // 由于组件异步化可能导致第一次没有加载到组件，所以需要在回调中调用
                dialog.show();
            });
        }
        if(valueobj.ecid.length > 0 && valueobj.cloudId.length <= 0){
            getInvoiceFid({method:"cloudId",ids:valueobj.ecid.join(",")}).then(res=>{
                const{status, targetIds}=res;
                if(status == 1){
                    fun(targetIds.split(","));
                }else{
                    // 接口出错
                }
            })
        }else if(valueobj.ecid.length > 0 && valueobj.cloudId.length > 0){
            fun(valueobj.cloudId)
        }else{
            fun([])
        }
        
       
    }

    getInvoiceCloudUrl = (fieldMark,fid) => {
        const { invoiceCloudInfo={} } = this.props.globalStore;
        let { baseProps } = this.props;
        const { detailtype,value } = baseProps;
        let comp={
            seq: {fieldMark},    // 可选，宿主生成的请求id，组件不处理该参数，仅在组件给宿主回传数据时原样返回
            name: "SelectInvoice",    // 必传，组件名，参考下方“组件列表”中的说明
            param: {    // 可选，宿主传过来的参数，具体格式参考下方“组件列表”中的说明
               hideHeader:true,
               multi:detailtype === 293 ? true : false,
               fids:fid||[]
            }
        };
        let url = `${invoiceCloudInfo.jsUrl}/corpInvoice/#/component?token=${invoiceCloudInfo.token}&src=EC&dev=0&baseUrl=${invoiceCloudInfo.baseUrl}&comp=${encodeURIComponent(JSON.stringify(comp))}`
        return url
    }
    
    getECID_FID=()=>{
        let {  fieldObj } = this.props;
        let specialobj  = fieldObj.specialobj ? mobx.toJS(fieldObj.specialobj) : [];
        let ecid=[];
        let cloudId=[];
        if(specialobj.length>0){
            specialobj.map(item=>{
                if(item.prop && item.prop.cloudId){
                    cloudId.push(item.prop.cloudId)
                }
                if(item.id){
                    ecid.push(item.id)
                }
            })
        }
        return {
            ecid:ecid,
            cloudId:cloudId
        }
    }
    
    //浏览数据定义获取表单字段数据
    getBrowserDataDefinition(relateFields, detailtype){
        const { rowIndex } = this.props;
    	let relateFieldValue = {};
        relateFields.map(field=>{
            const fieldid = field.split("_")[0];
            if(detailtype === 161 || detailtype === 162){
            }else{
                relateFieldValue[`field${fieldid}`] = FieldUtil.getRelateFieldValue(fieldid, rowIndex);
            }
        });
        relateFieldValue = {...relateFieldValue, ...FieldUtil.getRelateFieldShowName(relateFields, rowIndex)};
    	return relateFieldValue;
    }
    //设置浏览框表单参数
    extendBrowserProp(browserProp, fieldid, isDetail, detailtype){
        const { globalStore,fieldAttr,baseProps,fieldObj,rowIndex } = this.props;
        const { fielddbtype,browserattr={} } = fieldAttr;
        const { relateFieldid,sqlWhereField,browserParams = {} } = browserattr;
        const {tabs = [],hasAddGroup = false} = browserParams;
        if(tabs.length > 0) {
            browserProp.tabs = mobx.toJS(tabs);
        }
        //delete browserParams.tabs;
        const { viewAttr } = baseProps;
        const { variable } = fieldObj;
        const { commonParam, secLevelInfo } = globalStore;
        const { requestid,workflowid,formid,isbill,f_weaver_belongto_userid,f_weaver_belongto_usertype,wfTestStr,creater} = commonParam;
        if(hasAddGroup && detailtype === 17 && !isDetail){
        	browserProp.hasAddGroup = true;
        }
        if(detailtype === 1 || detailtype === 17){
            browserProp.isShowGroup = !isDetail;
            browserProp.canSelectAllUser = commonParam.allowAllPersonGroup;
        }
        if(detailtype === 141){
            browserProp.isShowSecLevel = browserParams.isShowSecLevel;
        }
        //设置文档浏览框添加按钮及公文浏览框条件
        const isWorkflowDoc = commonParam.isWorkflowDoc || false;
        const flowDocFieldId = commonParam.flowDocFieldId || 0;
        if(viewAttr > 1 && detailtype === 9 && !isDetail && isWorkflowDoc && flowDocFieldId == fieldid) {
            if(_.trim(baseProps.value).length === 0)
                browserProp.hasAddBtn = true;       //正文添加按钮
            browserProp.dataParams.isWord  = "1";
        }
        if(viewAttr > 1 && detailtype === 37) {
            browserProp.hasAddBtn = true;
        }
        if(viewAttr == 1){
            browserProp.simpleRO = true;
        }
        //请求接口参数相关扩展
      	let tempConditionDataParams = browserProp.conditionDataParams || {};
        let dataParams = browserProp.dataParams || {};
      	let relateFieldDatas = relateFieldid ? this.getBrowserDataDefinition(relateFieldid, detailtype) :{};
      	let completeParams = browserProp.completeParams || {}

        let customDataParam = variable.has("customDataParam") ? variable.get("customDataParam") : {};
      	let reqinfo = {
            wfid: workflowid,
            billid: formid,
            isbill: isbill,
            requestid: requestid,
            f_weaver_belongto_userid: f_weaver_belongto_userid,
            f_weaver_belongto_usertype: f_weaver_belongto_usertype,
            wf_isagent: commonParam.isagent,
            wf_beagenter: commonParam.beagenter,
            wfTestStr: wfTestStr,
            fieldid: fieldid,
            viewtype: isDetail ? "1" : "0",
            fromModule: "workflow",
            wfCreater:creater
        };
        if(detailtype === 226){     //SAP浏览按钮
            reqinfo = {...reqinfo, ...{fielddbtype, rowIndex}};
            browserProp.searchParams= {issearch:true};
        }
      	const browParams  = objectAssign({}, tempConditionDataParams,completeParams,dataParams, reqinfo, browserParams,relateFieldDatas,customDataParam);
        if(secLevelInfo && secLevelInfo.isOpenSec) {
            browParams.secretLevel = secLevelInfo.secLevel;
        }
        browserProp.conditionDataParams = browParams;
        browserProp.completeParams = browParams;
        browserProp.dataParams = browParams;
        browserProp.destDataParams = {...browserProp.destDataParams||{},...browParams, ...{fromModule: "workflow"}};

        if(detailtype === 16 || detailtype === 152 || detailtype === 171)
        	browserProp.linkUrl = `${browserProp.linkUrl}&fieldid=${fieldid}&requestid=`;
        //前端自定义浏览框属性覆盖
        let customBrowserProp = variable.has("customBrowserProp") ? variable.get("customBrowserProp") : {};
        for(let key in customBrowserProp){
            browserProp[key] = customBrowserProp[key];
        }
    }
    extendDateProp(baseProps){
        const detailtype = baseProps.detailtype;
        if(detailtype !== 2 && detailtype !== 19 && detailtype !== 290)
            return;
        const { cellObj,fieldObj } = this.props;
        let format = cellObj.format || {};
        const { variable } = fieldObj;
        baseProps.formatPattern = format["formatPattern"] || "";
        baseProps.noInput  = true;
        if(detailtype === 2){
            baseProps.startValue = variable.get("startDate") || "";
            baseProps.endValue = variable.get("endDate") || "";
        }
    }
    clickAddBtn = () => {
        const { globalStore,layoutStore,fieldMark,cellObj,baseProps } = this.props;
        const fieldid = cellObj.field.toString();
        const { commonParam, secLevelInfo={} } = globalStore;
        const { odocInfo } = layoutStore;
        const { detailtype } = baseProps;
        if(detailtype === 9 || detailtype === 37){
            if("docFieldId" in odocInfo && odocInfo.docFieldId.toString() === fieldid){      //公文字段创建直接切换到正文Tab
                if(commonParam.belongTest){
                    const { Modal } = getAntd();
                    Modal.warning({
                        title:getLabel(131329,'信息确认'),
                        content: getLabel(386200,"流程测试暂不支持创建公文!"),
                        okText: getLabel(83446,`确定`)
                    });
                    return;
                }else{
                    const needSwitch = window.oDocUtil.clickAddOdoc();
                    if(needSwitch)
                        WfForm.switchTab("odoc");
                }
            }else{  //创建文档
                OtherModule.createDoc(fieldMark, {...commonParam, secretLevel : secLevelInfo.secLevel});
            }
        }
	}

}
